package com.kelp.codetoolkit.service.impl

import com.intellij.database.model.DasColumn
import com.intellij.database.psi.DbTable
import com.intellij.database.util.DasUtil
import com.intellij.openapi.components.Service
import com.intellij.openapi.ui.Messages
import com.kelp.codetoolkit.constant.GlobalConfig
import com.kelp.codetoolkit.entity.ColumnInfo
import com.kelp.codetoolkit.entity.TableInfo
import com.kelp.codetoolkit.enums.MySQLToJavaTypeEnum
import com.kelp.codetoolkit.service.TableInfoHandleService
import com.kelp.codetoolkit.utils.NameHandleUtil
import kotlinx.datetime.LocalDate


/**
 * @author: liuyuebai
 * @date: 2024/8/2 17:31
 * @description:
 */
@Service
class TableInfoHandleServiceImpl: TableInfoHandleService {
    override fun parseToTableInfo(dbTable: DbTable): TableInfo {
        val tableInfo = TableInfo()
        tableInfo.setTableName(dbTable.name)
        val className = NameHandleUtil.initialUpperCase(dbTable.name)
        tableInfo.setClassName(className)
        tableInfo.setComment(dbTable.comment)
        val fullColumns = ArrayList<ColumnInfo>()
        val columns = DasUtil.getColumns(dbTable)
        for (column in columns) {
            val columnInfo = handleCommonColumns(column)
            if (columnInfo != null) {
                fullColumns.add(columnInfo)
            }
        }
        for (column in columns) {
            val pkColumn = handlePkColumn(column)
            if(pkColumn != null) {
                tableInfo.setPkColumn(pkColumn)
                break
            }
        }
        tableInfo.setFullColumns(fullColumns)
        return tableInfo
    }

    /**
     * 处理普通列
     */
    private fun handleCommonColumns(dasColumn: DasColumn):ColumnInfo? {
        if (DasUtil.isPrimary(dasColumn)){
            return null
        }
       return generateColumn(dasColumn)
    }

    private fun handlePkColumn(dasColumn: DasColumn):ColumnInfo? {
        if (!DasUtil.isPrimary(dasColumn)){
            return null
        }
        val generateColumn = generateColumn(dasColumn)
        if (DasUtil.isAuto(dasColumn)){
            generateColumn.setPkAutoIncrement(true)
        }
        return generateColumn
    }

    private fun generateColumn(dasColumn: DasColumn): ColumnInfo {
        val columnInfo = ColumnInfo()
        columnInfo.setColumnName(NameHandleUtil.convertCamelName(dasColumn.name))
        val dataType = dasColumn.dasType.toDataType()
        val typeEnum = MySQLToJavaTypeEnum.getJavaType(dataType.typeName)
        columnInfo.setColumnType(typeEnum.jFullType)
        columnInfo.setShortType(typeEnum.jShortType)
        dasColumn.comment?.let { columnInfo.setComment(it) }
        return columnInfo;
    }
}